package org.example.myleet.rosalind.utils;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;

public class FastaDownloader {

    private static final String UNIPROT_HOST = "https://rest.uniprot.org/unisave/";

    public static void main(String[] args) {
        String proteinIds = "P12763_A2HS_BOVIN\n" +
                "P00742_FA10_HUMAN\n" +
                "P19835_BAL_HUMAN\n" +
                "B8CH81\n" +
                "Q6GEK4\n" +
                "P14210_HGF_HUMAN\n" +
                "P17404_CHM1_BOVIN\n" +
                "P08709_FA7_HUMAN\n" +
                "Q8ZRE7\n" +
                "Q7TMB8\n" +
                "P01046_KNL1_BOVIN\n" +
                "P07204_TRBM_HUMAN\n" +
                "Q8P5E4\n" +
                "P10153_RNKD_HUMAN\n";
        String[] proteinIdList = proteinIds.split("\n");
        try {
            download(proteinIdList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void download(String[] proteinIds) throws IOException {
        for (String proteinId : proteinIds) {
            int underLineIdx = proteinId.indexOf("_");
            String uniProtId = underLineIdx > -1 ? proteinId.substring(0, underLineIdx) : proteinId;
            String tag = underLineIdx > -1 ? proteinId.substring(underLineIdx + 1) : "";
            URL url = new URL(UNIPROT_HOST + uniProtId + "?format=fasta");
            URLConnection connection = url.openConnection();
            InputStream is = connection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            boolean print = false;
            String line;
            while (null != (line = br.readLine()) && line.length() > 0) {
                if (line.startsWith(">")) {
                    if (print) {
                        break;
                    }
                    System.out.print(">");
                    System.out.println(proteinId);
                    line = br.readLine();
                    print = true;
                }
                System.out.println(line);
            }
            br.close();
        }
    }
}
